from __future__ import annotations
from .utils import html_escape

CSS = """
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; margin: 24px; color: #222; }
h1 { font-size: 22px; margin-bottom: 8px; }
h2 { font-size: 18px; margin-top: 28px; }
table { border-collapse: collapse; width: 100%; margin: 8px 0 16px 0; }
th, td { border: 1px solid #e5e7eb; padding: 8px 10px; text-align: left; vertical-align: top; }
th { background: #f8fafc; }
.code { background: #0b1020; color: #e5e7eb; padding: 12px; border-radius: 8px; overflow-x: auto; }
.badge { display: inline-block; background: #eef2ff; color: #3730a3; padding: 2px 6px; border-radius: 6px; font-size: 12px; border: 1px solid #c7d2fe; }
.summary { background: #f1f5f9; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px; }
"""

def render_report(problem_results, overall_total, output_path: str):
    parts = []
    parts.append("<!doctype html><html><head><meta charset='utf-8'>")
    parts.append(f"<style>{CSS}</style><title>CAB 简易报告</title></head><body>")
    parts.append("<h1>简易版 CAB 评估报告</h1>")
    parts.append("<div class='summary'>")
    parts.append(f"<div><span class='badge'>总分</span> <b>{overall_total:.2f}</b></div>")
    parts.append("</div>")
    for pr in sorted(problem_results, key=lambda x: x.problem_id):
        parts.append(f"<h2>Problem {pr.problem_id} &nbsp; <span class='badge'>函数：{html_escape(pr.func_name)}</span> &nbsp; <span class='badge'>总分：{pr.total_score:.2f}</span></h2>")
        parts.append("<table><thead><tr><th>指标</th><th>值</th><th>得分</th><th>说明</th></tr></thead><tbody>")
        for m in pr.metrics:
            parts.append(f"<tr><td>{html_escape(m.name)}</td><td>{html_escape(str(m.value))}</td><td>{m.score:.2f}</td><td>{html_escape(m.note)}</td></tr>")
        parts.append("</tbody></table>")
        parts.append("<div class='code'><pre><code>")
        parts.append(html_escape(pr.code))
        parts.append("</code></pre></div>")
    parts.append("</body></html>")
    html_text = "\n".join(parts)
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(html_text)
    return html_text
